即可阻斷噴嚏之行為。若要維繫感情,切勿輕易嘗試。
圖片來源:sohu
可惡,被斷招了。
本篇紀錄與前篇相關之不可思議事件:transitioncancel事件,並結合改造前面數篇之示例,紀錄transitioncancel事件發生之時間點與其他transition相關事件之關係。
此事件發生於元素之樣式屬性transition被移除之時。transitioncancel事件之發生時間將介於transitionrun事件發生後或transitionend事件發生前。
規範原文:
The transitioncancel event occurs when a transition is canceled.
MDN:
The transitioncancel event is fired if the transition is cancelled in either direction after the transitionrun event occurs and before the transitionend is fired.
以下示例改造前篇之示例,並同時於文字顯示處顯示當前觸發之事件。
const keys = document.querySelector(".keys");
const text = document.querySelector(".text");
function showPressedKeys(event) {
  const key = event.key;
  const singleKey = document.createElement("div");
  singleKey.classList.add("key-down");
  singleKey.textContent = `${key}`;
  keys.insertBefore(singleKey, null);
  setTimeout(() => {
    singleKey.classList.add("heater");
  }, 1000);
  setTimeout(() => {
    singleKey.style.transition = "none";
  }, 3000);
}
window.addEventListener("keydown", showPressedKeys);
keys.addEventListener("transitionend", (event) => {
  text.textContent = "END事件發生";
  event.target.textContent = "🤪";
});
keys.addEventListener("transitioncancel", (event) => {
  text.textContent = "CANCEL事件發生";
  event.target.textContent = "❌";
});
keys.addEventListener("transitionstart", () => {
  text.textContent = "START事件發生";
});
keys.addEventListener("transitionrun", () => {
  text.textContent = "RUN事件發生";
});
修改之術式註釋如下:
選取文字顯示處元素。
const text = document.querySelector(".text");
在函式之術showPressedKeys中,添一定時裝置,於3秒後將鍵石之樣式屬性transition更改為none,意即取消樣式屬性transition。
setTimeout(() => {
    singleKey.style.transition = "none";
}, 3000);
另原鍵石之transition樣式設定如下,意即border樣式於1秒後轉變,且轉變之時長為3秒:
.key-down {
  transition: border 3s 1s;
}
綜合上述設定,可知時程為:按壓鍵石→1秒後→設定鍵石加熱器→1秒後→鍵石開始加熱→1秒後→取消加熱器
設定四事件觀測器於鍵石容器元素,若鍵石容器元素或其子元素發生事件,則於文字顯示處顯示事件之文字,若發生之事件為transitionend事件,則將鍵石符文以詭異黃色人類臉龐覆蓋;若發生之事件為transitioncancel事件,則將鍵石符文以血紅交叉覆蓋。
keys.addEventListener("transitionend", (event) => {
  text.textContent = "END事件發生";
  event.target.textContent = "🤪";
});
keys.addEventListener("transitioncancel", (event) => {
  text.textContent = "CANCEL事件發生";
  event.target.textContent = "❌";
});
keys.addEventListener("transitionstart", () => {
  text.textContent = "START事件發生";
});
keys.addEventListener("transitionrun", () => {
  text.textContent = "RUN事件發生";
});
按壓鍵石ctrl後,1秒後發生transitionrun事件,再1秒後發生transitionstart事件,再1秒後transition樣式遭取消而發生transitioncancel事件。
此符合規範紀錄之transitioncancel事件發生時間介於transitionrun事件發生後或transitionend事件發生前,亦符合前篇紀錄之transitionend事件不觸發之狀況。
規範原文:
In the case where a transition is removed before completion, such as if the transition-property is removed, then the event will not fire.
因此transitioncancel與transitionend事件為互斥之關係。
MDN:
If the transitioncancel event is fired, the transitionend event will not fire.
https://github.com/CReticulata/2024ithome/tree/main/Day23
元素:element
鼠輩:滑鼠
鍵石:鍵盤按鍵